package com.instalinks.android.apps.smspostservice;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;

import com.instalinks.android.apps.smspostservice.helper.AppConfig;
import com.instalinks.android.apps.smspostservice.helper.Constants;
import com.instalinks.android.lib.AppHelper;
import com.instalinks.android.apps.smspostservice.R;
import com.instalinks.android.lib.*;
public class SplashActivity extends Activity {

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		initialize();
	}

	private void initialize() {
		new Thread() {
			@Override
			public void run() {
				try {
					int waited = 0;
					while (waited < 1000) {
						sleep(100);
						waited += 100;
					}
				} catch (InterruptedException e) {
					// do nothing
				} finally {
					processUIThread();
				}
			}
		}.start();
	}

	private void processUIThread() {
		SplashActivity.this.runOnUiThread(new Runnable() {

			@Override
			public void run() {
				doProcess();
			}
		});
	}

	private void doProcess() {
		try {
			AppConfig appCfg = new AppConfig(this);
			
			if(!appCfg.isBaseServiceRunning()){
				jumpToError(LibConstants.Error.BASE_APP_ERR);
				return;
			}

			if (appCfg.getDataPostUrl().length() == 0) {
				try {
					appCfg.setDataPostUrl(appCfg.getAppUrl());
				} catch (Exception e) {
					appCfg.alert("Error loading App URL. Please restart the application.");
					this.finish();
					return;
				}
			}

			String email = appCfg.getEmail();
			// email = ""; // FOR TESTING
			if (email.trim().length() == 0) {
				jumpToError(Constants.ERR_NOEMAIL);
			} else if (appCfg.isConfigExists()
					&& appCfg.isSubscribedFlag()
					&& appCfg.getSubscriberId().equalsIgnoreCase(
							appCfg.getSubscriberIdFromConfig())) {
				jumpToHome();
			} else {
				boolean result = appCfg.updateConfigFromHost();
				if(result){
					if(appCfg.isSubscribedFlag()){
						jumpToHome();
					}else{
						jumpToError(Constants.ERR_USER_REGISTRATION);
					}
				}else{
					jumpToError(Constants.ERR_CONFIG_DOWNLOAD);
				}
			}
		} catch (Exception e) {
			AppHelper.alert(getApplicationContext(),
					"Problem starting the application.");
			this.finish();
			Log.e("[SMSPOSTSERVICE]", e.getMessage());
		}
	}

	private void jumpToHome() {
		Intent i = new Intent();
		i.setClassName(getApplicationContext().getPackageName(),
				HomeActivity.class.getName());

		startActivity(i);
		this.finish();
	}

	private void jumpToError(String error) {
		Intent i = new Intent();
		i.setClassName(getApplicationContext().getPackageName(),
				ErrorActivity.class.getName());

		Bundle bundle = new Bundle();
		bundle.putString("error", error);
		i.putExtras(bundle);

		startActivity(i);
		this.finish();
	}
}
